package com.demo.accessibility.floatwindows

import android.util.Log
import android.view.View
import android.view.accessibility.AccessibilityEvent
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.ToastUtils
import com.demo.accessibility.R
import com.demo.accessibility.base.BaseFloatWindowManager
import com.demo.accessibility.bean.ExpressInfoBean
import com.demo.accessibility.service.NurseHelperService
import com.demo.accessibility.utils.AccessibilityUtils

/**
 * ================================================
 * 抓取妈妈驿站的页面信息
 * Created by ligang on 2024/5/2
 * ================================================
 */
class GatherYistationFloatWindowManager : BaseFloatWindowManager() {
    companion object {
        private const val TAG = "GatherYistationFloatWindowManager"
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { GatherYistationFloatWindowManager() }
    }

    override fun provideFloatView() = R.layout.view_gather_yistation_info

    private fun rootInActiveWindow() = NurseHelperService.instance?.rootInActiveWindow

    private var mInfoText: TextView? = null

    override fun initView(floatView: View) {
        mInfoText = floatView.findViewById(R.id.tv_info)
        floatView.findViewById<View>(R.id.btn_back_app).setOnClickListener {
            AccessibilityUtils.returnApp()
            remove()
        }
    }

//    private val mExpressMap = mutableMapOf<String, ExpressInfoBean>()

    private var isOpen = false
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        NurseHelperService.instance?.printRootView()
        when (event?.eventType) {
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                val packageName = event.packageName?.toString()
                val className = event.className?.toString()

                Log.e("============", "packageName：${packageName},className: $className")
                // 检查当前活动窗口的包名和类名是否符合你要采集信息的 Activity
                if (packageName == "cn.com.yto56.yistation" && className == "com.yto.station.op.ui.activity.OpTabActivity") {
                    // 在这里进行自动采集
                    isOpen = true
                    Log.e(TAG, "准备采集")
                } else {
                    isOpen = false
                    Log.e(TAG, "关闭采集")
                }
            }

            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {
                if (isOpen) {
                    gatherInfo()
                }
            }
        }
    }

    private fun gatherInfo() {
        // 定位 扫描记录
        val scanRecordTextNoteInfo = AccessibilityUtils.findNoteInfoByStartText(
            mutableListOf("扫描记录"),
            rootInActiveWindow()
        )

        scanRecordTextNoteInfo?.let {
            NurseHelperService.instance?.printAll(it, 0)
            val child = scanRecordTextNoteInfo.parent.parent.getChild(2).getChild(0)
            val textList = mutableListOf<String>()
            for (i in 0 until child.childCount) {
                val child2 = child.getChild(i)
                if (child2.className == TextView::class.java.name) {
                    textList.add(child2.text?.toString()?.replace(" ", "") ?: "")
                }
            }
            if (textList.size == 4) {
//                val no = textList[2]
//                if (!mExpressMap.contains(no)) {
//                    mExpressMap[no] = ExpressInfoBean().apply {
//                        phone = textList[0]
//                        name = textList[1]
//                        expressNo = textList[2]
//                        pickupCode = textList[3]
//                    }
//                    ToastUtils.showLong("发现目标：\n${JSON.toJSONString(mExpressMap[no])}")
//                    mInfoText?.text = JSON.toJSONString(mExpressMap[no])
//                    Log.e("=========>>>>", JSON.toJSONString(mExpressMap[no]))
//                }
                val expressInfoBean = ExpressInfoBean().apply {
                    phone = textList[0]
                    name = textList[1]
                    expressNo = textList[2]
                    pickupCode = textList[3]
                }
                ToastUtils.showLong("发现目标：\n${JSON.toJSONString(expressInfoBean)}")
                mInfoText?.text = JSON.toJSONString(expressInfoBean)
            }
        }
    }
}